package gblc.client;

import java.io.*;
import java.net.*;

import android.util.Log;

 public class SocketClient {
    static Socket client;
    
    public SocketClient(String site, int port){
        try{
            client = new Socket(site,port);
            client.setSoTimeout(5000);
          }catch (UnknownHostException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }catch (Exception e){
        	e.printStackTrace();
        }      
    }
    
    public String sendMsg(String msg){
        try{

			OutputStream os = client.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(os);
			BufferedWriter bw = new BufferedWriter(osw);
			bw.write(msg);
			bw.flush();  
			Log.d("socket","send "+msg);
			InputStream is = client.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String s = "";
				char [] buff = new char[8];
				br.read(buff,0,8);
				String strLen = String.format("%c%c%c%c%c%c", buff[2],buff[3],buff[4],buff[5],buff[6],buff[7]);
				int len = Integer.parseInt(strLen.trim());
				char [] backArray = new char[len];
				br.read(backArray,8,len-8);
				String strBack = new String(backArray);
				String strHead = new String(buff);
				s = strHead+strBack;
				Log.d("socket","receive "+s);
            return s;
        }catch(IOException e){
        	 return e.toString();
        } catch(Exception e){
            return e.toString();
        }

    }
    
    public void closeSocket(){
        try{
            client.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

}
